package com.portal.incurridos.persistence.dao.impl;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Component;

import com.portal.incurridos.persistence.dao.ProjectDao;
import com.portal.incurridos.persistence.enumeration.StateRecordEnum;
import com.portal.incurridos.persistence.enumeration.StateTransactionEnum;
import com.portal.incurridos.persistence.wall.Project;

/**
 * @author Alan Dávila
 * e-mail ustargab@gmail.com
 * date 15/11/2013 00:09:22
 */
@Component("projectDaoImpl")
public class ProjectDaoHibernateImpl implements ProjectDao {

	/**
	 * Managment bean of dao layer.
	 */
	@Resource(name = "sessionFactory")
    private SessionFactory factoria;

	/* (non-Javadoc)
	 * @see com.portal.incurridos.persistence.dao.ProjectDao#create(com.portal.incurridos.persistence.wall.Project)
	 */
	public final Project create(final Project project) {
		Session session = null;
		Transaction tx = null;
		Project projectOut = project;
		try {
			session = factoria.openSession();
			tx = session.beginTransaction();
			session.save(projectOut);
			tx.commit();
			session.close();
		} catch (Exception e) {
			projectOut = null;
		}
		return projectOut;
	}

	/* (non-Javadoc)
	 * @see com.portal.incurridos.persistence.dao.ProjectDao#update(com.portal.incurridos.persistence.wall.Project)
	 */
	public final StateTransactionEnum update(final Project project) {
		Session session = null;
		Transaction tx = null;
		try {
			session = factoria.openSession();
			tx = session.beginTransaction();
			session.update(project);
			tx.commit();
			session.close();
		} catch (Exception e) {
			return StateTransactionEnum.ERROR;
		}
		return StateTransactionEnum.UPDATED;
	}

	/* (non-Javadoc)
	 * @see com.portal.incurridos.persistence.dao.ProjectDao#delete(com.portal.incurridos.persistence.wall.Project)
	 */
	public final StateTransactionEnum delete(final Project project) {
		Session session = null;
		Transaction tx = null;
		try {
			project.setState(StateRecordEnum.DISABLE.getState());
			session = factoria.openSession();
			tx = session.beginTransaction();
			session.update(project);
			tx.commit();
			session.close();
		} catch (Exception e) {
			return StateTransactionEnum.ERROR;
		}
		return StateTransactionEnum.DELETED;
	}

	/* (non-Javadoc)
	 * @see com.portal.incurridos.persistence.dao.ProjectDao#get(java.lang.Integer)
	 */
	public final Project get(final Integer project) {
		Session session = null;
		Project projectOut = null;
		try {
			session = factoria.openSession();
			projectOut = (Project) session.get(Project.class, project);
			session.close();
		} catch (Exception e) {
			projectOut = null;
		}
		return projectOut;
	}

}
